<template>
  <div class="post-loan-track">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>贷后跟踪</h3>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddTrack">新增跟踪记录</el-button>
            <el-button type="success" @click="handleExport">导出</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="贷款编号">
          <el-input v-model="searchForm.loanNo" placeholder="请输入贷款编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="风险等级">
          <el-select v-model="searchForm.riskLevel" placeholder="请选择风险等级" clearable>
            <el-option label="正常" value="normal"></el-option>
            <el-option label="关注" value="attention"></el-option>
            <el-option label="次级" value="secondary"></el-option>
            <el-option label="可疑" value="doubtful"></el-option>
            <el-option label="损失" value="loss"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跟踪时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="loanNo" label="贷款编号" width="180"></el-table-column>
        <el-table-column prop="customerName" label="客户名称" width="120"></el-table-column>
        <el-table-column prop="trackDate" label="跟踪日期" width="120"></el-table-column>
        <el-table-column prop="trackPerson" label="跟踪人员" width="120"></el-table-column>
        <el-table-column prop="trackType" label="跟踪方式" width="120">
          <template #default="scope">
            {{ getTrackType(scope.row.trackType) }}
          </template>
        </el-table-column>
        <el-table-column prop="riskLevel" label="风险等级" width="100">
          <template #default="scope">
            <el-tag :type="getRiskLevelType(scope.row.riskLevel)">{{ getRiskLevelText(scope.row.riskLevel) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="warningLevel" label="预警等级" width="100">
          <template #default="scope">
            <el-tag :type="getWarningLevelType(scope.row.warningLevel)">{{ getWarningLevelText(scope.row.warningLevel) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="nextTrackDate" label="下次跟踪日期" width="120"></el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑跟踪记录对话框 -->
    <el-dialog 
      v-model="trackDialogVisible" 
      :title="trackForm.id ? '编辑跟踪记录' : '新增跟踪记录'"
      width="600px"
    >
      <el-form :model="trackForm" label-width="100px" :rules="trackRules" ref="trackFormRef">
        <el-form-item label="贷款编号" prop="loanNo">
          <el-select v-model="trackForm.loanNo" placeholder="请选择贷款" filterable style="width: 100%">
            <el-option
              v-for="item in loanOptions"
              :key="item.loanNo"
              :label="`${item.loanNo} - ${item.customerName}`"
              :value="item.loanNo"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跟踪方式" prop="trackType">
          <el-select v-model="trackForm.trackType" placeholder="请选择跟踪方式" style="width: 100%">
            <el-option label="实地走访" value="visit"></el-option>
            <el-option label="电话沟通" value="phone"></el-option>
            <el-option label="视频会议" value="video"></el-option>
            <el-option label="邮件往来" value="email"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跟踪日期" prop="trackDate">
          <el-date-picker v-model="trackForm.trackDate" type="date" placeholder="选择跟踪日期" style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="跟踪人员" prop="trackPerson">
          <el-select v-model="trackForm.trackPerson" placeholder="请选择跟踪人员" style="width: 100%">
            <el-option
              v-for="item in personOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="风险等级" prop="riskLevel">
          <el-select v-model="trackForm.riskLevel" placeholder="请选择风险等级" style="width: 100%">
            <el-option label="正常" value="normal"></el-option>
            <el-option label="关注" value="attention"></el-option>
            <el-option label="次级" value="secondary"></el-option>
            <el-option label="可疑" value="doubtful"></el-option>
            <el-option label="损失" value="loss"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预警等级" prop="warningLevel">
          <el-select v-model="trackForm.warningLevel" placeholder="请选择预警等级" style="width: 100%">
            <el-option label="无预警" value="none"></el-option>
            <el-option label="一级预警" value="level1"></el-option>
            <el-option label="二级预警" value="level2"></el-option>
            <el-option label="三级预警" value="level3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跟踪内容" prop="content">
          <el-input v-model="trackForm.content" type="textarea" rows="4" placeholder="请输入跟踪内容"></el-input>
        </el-form-item>
        <el-form-item label="风险描述" prop="riskDescription">
          <el-input v-model="trackForm.riskDescription" type="textarea" rows="3" placeholder="请输入风险描述"></el-input>
        </el-form-item>
        <el-form-item label="处置措施" prop="measures">
          <el-input v-model="trackForm.measures" type="textarea" rows="3" placeholder="请输入处置措施"></el-input>
        </el-form-item>
        <el-form-item label="下次跟踪日期" prop="nextTrackDate">
          <el-date-picker v-model="trackForm.nextTrackDate" type="date" placeholder="选择下次跟踪日期" style="width: 100%"></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="trackDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTrack">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看跟踪记录对话框 -->
    <el-dialog v-model="viewDialogVisible" title="跟踪记录详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="贷款编号">{{ currentTrack.loanNo }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ currentTrack.customerName }}</el-descriptions-item>
        <el-descriptions-item label="跟踪方式">{{ getTrackType(currentTrack.trackType) }}</el-descriptions-item>
        <el-descriptions-item label="跟踪日期">{{ currentTrack.trackDate }}</el-descriptions-item>
        <el-descriptions-item label="跟踪人员">{{ currentTrack.trackPerson }}</el-descriptions-item>
        <el-descriptions-item label="风险等级">
          <el-tag :type="getRiskLevelType(currentTrack.riskLevel)">{{ getRiskLevelText(currentTrack.riskLevel) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="预警等级">
          <el-tag :type="getWarningLevelType(currentTrack.warningLevel)">{{ getWarningLevelText(currentTrack.warningLevel) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="下次跟踪日期">{{ currentTrack.nextTrackDate }}</el-descriptions-item>
        <el-descriptions-item label="跟踪内容" :span="2">{{ currentTrack.content }}</el-descriptions-item>
        <el-descriptions-item label="风险描述" :span="2">{{ currentTrack.riskDescription }}</el-descriptions-item>
        <el-descriptions-item label="处置措施" :span="2">{{ currentTrack.measures }}</el-descriptions-item>
      </el-descriptions>
      <div class="track-images" v-if="currentTrack.images && currentTrack.images.length">
        <h4>现场照片</h4>
        <el-image
          v-for="(image, index) in currentTrack.images"
          :key="index"
          :src="image"
          :preview-src-list="currentTrack.images"
          fit="cover"
          class="track-image"
        ></el-image>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { postloanTrackApi } from '@/api/postloan'

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  loanNo: '',
  customerName: '',
  riskLevel: '',
  dateRange: []
})

// 跟踪记录表单
const trackDialogVisible = ref(false)
const trackFormRef = ref(null)
const trackForm = reactive({
  id: '',
  loanNo: '',
  trackType: '',
  trackDate: '',
  trackPerson: '',
  riskLevel: '',
  warningLevel: '',
  content: '',
  riskDescription: '',
  measures: '',
  nextTrackDate: ''
})

// 表单校验规则
const trackRules = {
  loanNo: [{ required: true, message: '请选择贷款', trigger: 'change' }],
  trackType: [{ required: true, message: '请选择跟踪方式', trigger: 'change' }],
  trackDate: [{ required: true, message: '请选择跟踪日期', trigger: 'change' }],
  trackPerson: [{ required: true, message: '请选择跟踪人员', trigger: 'change' }],
  riskLevel: [{ required: true, message: '请选择风险等级', trigger: 'change' }],
  warningLevel: [{ required: true, message: '请选择预警等级', trigger: 'change' }],
  content: [{ required: true, message: '请输入跟踪内容', trigger: 'blur' }],
  nextTrackDate: [{ required: true, message: '请选择下次跟踪日期', trigger: 'change' }]
}

// 贷款选项
const loanOptions = ref([])

// 人员选项
const personOptions = ref([])

// 查看对话框
const viewDialogVisible = ref(false)
const currentTrack = ref({})

// 获取跟踪方式文本
const getTrackType = (type) => {
  const types = {
    visit: '实地走访',
    phone: '电话沟通',
    video: '视频会议',
    email: '邮件往来'
  }
  return types[type] || '未知'
}

// 获取风险等级类型
const getRiskLevelType = (level) => {
  const types = {
    normal: 'success',
    attention: 'warning',
    secondary: 'danger',
    doubtful: 'danger',
    loss: 'danger'
  }
  return types[level] || 'info'
}

// 获取风险等级文本
const getRiskLevelText = (level) => {
  const texts = {
    normal: '正常',
    attention: '关注',
    secondary: '次级',
    doubtful: '可疑',
    loss: '损失'
  }
  return texts[level] || '未知'
}

// 获取预警等级类型
const getWarningLevelType = (level) => {
  const types = {
    none: 'info',
    level1: 'success',
    level2: 'warning',
    level3: 'danger'
  }
  return types[level] || 'info'
}

// 获取预警等级文本
const getWarningLevelText = (level) => {
  const texts = {
    none: '无预警',
    level1: '一级预警',
    level2: '二级预警',
    level3: '三级预警'
  }
  return texts[level] || '未知'
}

// 获取数据
const fetchData = () => {
  loading.value = true
  
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    loanNo: searchForm.loanNo,
    customerName: searchForm.customerName,
    riskLevel: searchForm.riskLevel,
    startDate: searchForm.dateRange && searchForm.dateRange.length > 0 ? searchForm.dateRange[0] : '',
    endDate: searchForm.dateRange && searchForm.dateRange.length > 0 ? searchForm.dateRange[1] : ''
  }
  
  postloanTrackApi.getList(params).then(res => {
    tableData.value = res.data.rows
    total.value = res.data.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 获取贷款选项
const fetchLoanOptions = () => {
  // 模拟API调用
  setTimeout(() => {
    loanOptions.value = Array.from({ length: 10 }, (_, index) => ({
      loanNo: `LOAN${String(2023000 + index + 1).padStart(7, '0')}`,
      customerName: `客户${index + 1}`
    }))
  }, 300)
}

// 获取人员选项
const fetchPersonOptions = () => {
  // 模拟API调用
  setTimeout(() => {
    personOptions.value = Array.from({ length: 5 }, (_, index) => ({
      id: index + 1,
      name: `跟踪员${index + 1}`
    }))
  }, 300)
}

// 新增跟踪记录
const handleAddTrack = () => {
  trackForm.id = ''
  trackForm.loanNo = ''
  trackForm.trackType = ''
  trackForm.trackDate = ''
  trackForm.trackPerson = ''
  trackForm.riskLevel = ''
  trackForm.warningLevel = ''
  trackForm.content = ''
  trackForm.riskDescription = ''
  trackForm.measures = ''
  trackForm.nextTrackDate = ''
  
  trackDialogVisible.value = true
  fetchLoanOptions()
  fetchPersonOptions()
}

// 编辑跟踪记录
const handleEdit = (row) => {
  Object.assign(trackForm, row)
  trackDialogVisible.value = true
  fetchLoanOptions()
  fetchPersonOptions()
}

// 提交跟踪记录
const submitTrack = () => {
  trackFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      
      const formData = {
        loanNo: trackForm.loanNo,
        trackDate: trackForm.trackDate,
        trackPerson: trackForm.trackPerson,
        trackMethod: trackForm.trackType,
        contactPerson: trackForm.contactPerson,
        contactPhone: trackForm.contactPhone,
        riskLevel: trackForm.riskLevel,
        financialStatus: trackForm.financialStatus,
        operationStatus: trackForm.operationStatus,
        trackContent: trackForm.content,
        trackResult: trackForm.trackResult,
        suggestion: trackForm.suggestion,
        nextTrackDate: trackForm.nextTrackDate,
        nextTrackMethod: trackForm.nextTrackMethod,
        attachments: trackForm.attachments
      }
      
      if (trackForm.id) {
        // 更新
        postloanTrackApi.update({
          id: trackForm.id,
          ...formData
        }).then(() => {
          ElMessage.success('更新成功')
          trackDialogVisible.value = false
          fetchData()
        }).finally(() => {
          loading.value = false
        })
      } else {
        // 新增
        postloanTrackApi.add(formData).then(() => {
          ElMessage.success('添加成功')
          trackDialogVisible.value = false
          fetchData()
        }).finally(() => {
          loading.value = false
        })
      }
    }
  })
}

// 删除跟踪记录
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该跟踪记录吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    postloanTrackApi.delete(row.id).then(() => {
      ElMessage.success('删除成功')
      fetchData()
    }).finally(() => {
      loading.value = false
    })
  }).catch(() => {})
}

// 查看跟踪记录
const handleView = (row) => {
  loading.value = true
  postloanTrackApi.getDetail(row.id).then(res => {
    const detail = res.data
    currentTrack.value = {
      ...row,
      content: detail.trackContent,
      riskDescription: detail.riskDescription,
      measures: detail.measures,
      images: detail.attachments.map(attachment => attachment.url)
    }
    viewDialogVisible.value = true
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 导出
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.post-loan-track {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.track-images {
  margin-top: 20px;
}

.track-image {
  width: 120px;
  height: 120px;
  margin-right: 10px;
  margin-bottom: 10px;
}
</style> 